<template>
  <div class="p-4">
    <div class="add_btn">
      <a-button type="primary" v-if="isButtonVisible(10000001)" @click="showAddModal"
        >添加公司</a-button
      >
    </div>
    <Table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="pagination"
      @change="tableChangeFn"
    >
      <template #action="{ record }">
        <div class="table_action">
          <div @click="editFn(record)" v-if="isButtonVisible(10000002)">修改</div>
          <Popconfirm
            :title="`您确定要删除${record.name}吗？`"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirmDeletion(record)"
          >
            <div v-if="isButtonVisible(10000003)">删除</div>
          </Popconfirm>
          <div @click="menuPermissions(record)" v-if="isButtonVisible(10000004)">菜单权限</div>
        </div>
      </template>
    </Table>
    <BasicModal
      v-model:visible="addVisible"
      :title="isEdit == false ? '添加公司' : '编辑公司'"
      @ok="onSubmit"
    >
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <!-- <div v-if="popStatic == 1"> -->
        <FormItem ref="name" label="公司名称" name="name">
          <Input v-model:value="formState.name" placeholder="请输入公司名称" />
        </FormItem>
        <FormItem ref="projectCode" label="项目编号前缀" name="projectCode">
          <Input v-model:value="formState.projectCode" placeholder="请输入项目编号前缀" />
        </FormItem>
        <FormItem label="所在省份" name="provinceId">
          <Select
            allowClear
            v-model:value="formState.provinceId"
            placeholder="请选择所在省份"
            @change="selectProvinceId"
          >
            <SelectOption v-for="(item, index) in provinceArr" :value="item.id" :key="index">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="所在城市" name="cityId" v-if="showCity">
          <Select
            allowClear
            v-model:value="formState.cityId"
            placeholder="请选择所在城市"
            @change="selectCrty"
            :disabled="formState.provinceId ? false : true"
          >
            <SelectOption v-for="(item, index) in cityArr" :value="item.id" :key="index">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="所在区县" name="districtId" v-if="showdistric">
          <Select
            allowClear
            v-model:value="formState.districtId"
            placeholder="请选择所在区县"
            :disabled="formState.cityId ? false : true"
          >
            <SelectOption v-for="(item, index) in districtArr" :value="item.id" :key="index">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="详细地址" name="address">
          <Input v-model:value="formState.address" placeholder="请输入公司详细地址" />
        </FormItem>
        <!-- </div> -->
      </Form>
    </BasicModal>
    <SelectTree ref="selectTree"></SelectTree>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import { Table, Form, Input, FormItem, Select, SelectOption, Popconfirm } from 'ant-design-vue';
  import {
    companySearch,
    getProvince,
    getCity,
    getDistrict,
    addCompany,
    deleteCompany,
    editCompany,
  } from '/@/api/api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal } from '/@/components/Modal';
  import SelectTree from './components/selectTree.vue';
  import { useRoute } from 'vue-router';
  let route = useRoute();
  const isButtonVisible = (id) => {
    let rulesArr = route?.meta?.rules?.map((rule) => rule.id) || [];
    return rulesArr.includes(id);
  };

  const { createMessage } = useMessage();

  const dataSource = ref([]);

  const columns = ref([
    {
      title: '项目编号前缀',
      dataIndex: 'projectCode',
      key: 'projectCode',
      fixed: 'left',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '地址',
      dataIndex: 'addressAll',
      key: 'addressAll',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
      width: 100,
    },
  ]);
  // 设置菜单权限
  const selectTree = ref(); //合同
  const menuPermissions = (record) => {
    selectTree.value.init({
      comid: record.id,
    });
  };
  const formRef = ref();
  const formState: any = reactive({
    name: '',
    provinceId: '',
    cityId: '',
    districtId: '',
    address: '',
    projectCode: '',
  });
  const rules = {
    name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    provinceId: [{ required: true, message: '请选择所在省份' }],
    cityId: [{ required: true, message: '请选择所在城市' }],
    districtId: [{ required: true, message: '请选择所在区县' }],
    address: [{ required: true, message: '请输入地址' }],
    projectCode: [{ required: true, message: '请输入项目编号前缀' }],
  };
  // 编辑
  const isEdit = ref(false);
  const editData = ref({});
  const editFn = (e) => {
    isEdit.value = true;
    addVisible.value = true;
    editData.value = e;
    formState.provinceId = e.provinceId;
    selectProvinceId(e.cityId);
    formState.name = e.name;
    formState.cityId = e.cityId;
    formState.districtId = e.districtId;
    selectCrty(e.districtId);
    formState.address = e.address;
    formState.projectCode = e.projectCode;
  };
  // 确认删除
  const confirmDeletion = (e) => {
    deleteCompany({
      ...e,
    }).then(() => {
      createMessage.success('删除成功');
      getTableData();
    });
  };
  // 地址相关
  const provinceArr = ref([]);
  const cityArr = ref([]);
  const districtArr = ref([]);
  const showCity = ref(true);
  const showdistric = ref(true);

  // 选择完省份 selectCrty
  const selectProvinceId = (id?: any) => {
    getCity({
      provinceId: formState.provinceId,
    }).then((res) => {
      cityArr.value = res;
      if (isEdit.value == false) {
        formState.districtId = '';
        formState.cityId = '';
      } else {
        formState.cityId = id;
      }
      if (res.length == 0) {
        formState.cityId = formState.provinceId;
        formState.districtId = formState.provinceId;
        showCity.value = false;
        showdistric.value = false;
      } else {
        showCity.value = true;
        showdistric.value = true;
      }
    });
  };
  const selectCrty = (id?: any) => {
    getDistrict({
      cityId: formState.cityId,
    }).then((res) => {
      districtArr.value = res;
      if (isEdit.value == true) {
        formState.districtId = id;
      } else {
        formState.districtId = '';
      }
      showdistric.value = true;
      if (res.length == 0) {
        formState.districtId = formState.cityId;
        showdistric.value = false;
      }
    });
  };
  // 根据id查找相对应的文字
  const provinceIdTotxt = async (kind: string, id: any, proId?: any, cityId?: any) => {
    if (!id) {
      return '';
    }
    if (kind === 'province') {
      const province = provinceArr.value.find((province) => province.id === id);
      return province ? province.name : '';
    }

    if (kind === 'city') {
      const res = await getCity({ provinceId: proId });
      const city = res.find((city) => city.id === id);
      return city ? city.name : '';
    }

    if (kind === 'distri') {
      const res = await getDistrict({ cityId: cityId });
      const district = res.find((district) => district.id === id);
      return district ? district.name : '';
    }
  };

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        if (isEdit.value == true) {
          editCompany({
            ...formState,
            id: editData.value.id,
          }).then(() => {
            createMessage.success('编辑成功');
            resetForm();
            addVisible.value = false;
            getTableData();
          });
        } else {
          addCompany({
            ...formState,
          }).then(() => {
            createMessage.success('添加成功');
            resetForm();
            addVisible.value = false;
            getTableData();
          });
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formState.provinceId = '';
    formState.name = '';
    formState.cityId = '';
    formState.districtId = '';
    formState.address = '';
    formState.projectCode = '';
  };
  // 弹窗相关
  const addVisible = ref<boolean>(false);
  const showAddModal = () => {
    resetForm();
    isEdit.value = false;
    addVisible.value = true;
  };

  const getTableData = async () => {
    try {
      const response = await companySearch({
        page: pagination.value.current,
        limit: pagination.value.pageSize,
      });
      pagination.value.total = response.total;
      dataSource.value = response.items;
      for (const item of dataSource.value) {
        const provinceName = await provinceIdTotxt('province', item.provinceId);
        const cityName = await provinceIdTotxt('city', item.cityId, item.provinceId);
        const districtName = await provinceIdTotxt(
          'distri',
          item.districtId,
          item.provinceId,
          item.cityId,
        );
        item.addressAll = provinceName + cityName + districtName + item.address;
      }
    } catch (error) {
      console.error('An error occurred while fetching data:', error);
    }
  };
  onMounted(() => {
    getTableData();
    getProvince().then((res) => {
      provinceArr.value = res;
    });
  });

  //分页器对象
  const pagination = ref({
    current: '1',
    pageSize: '10',
    pageSizeOptions: ['10', '20', '50', '100'],
    total: 0,
    showTotal: (totals) => `总${totals}条数据`,
    showSizeChanger: true,
  });

  // table变化时出发  筛选/跳转
  const tableChangeFn = (e) => {
    pagination.value.current = String(e.current);
    pagination.value.pageSize = String(e.pageSize);
    console.log(e, 'e');
    getTableData();
  };
</script>

<style lang="less" scoped>
  .add_btn {
    margin: 0 0 15px 0;
  }
  .form_box {
    padding: 20px;
  }
  .table_action {
    color: rgb(25, 144, 255);
    div:first-child {
      margin-right: 5px;
    }
    div {
      cursor: pointer;
    }
  }
</style>
